package com.xmy.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

// DCL双重校验锁
public class LazyMan {
    private LazyMan(){
        if (lazyMan!=null)
            throw new RuntimeException("不要试图用反射破解单例！");
    }

    private static LazyMan lazyMan;

    public static LazyMan getInstance(){
        if (lazyMan==null){
            synchronized (LazyMan.class) {
                if (lazyMan==null) {
                    lazyMan = new LazyMan();
                    return lazyMan;
                }
            }
        }
        return lazyMan;
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        LazyMan instance1 = LazyMan.getInstance(); //通过正常方式获取LazyMan对象
        Constructor<LazyMan> constructor = LazyMan.class.getDeclaredConstructor(null);
        constructor.setAccessible(true);
//        LazyMan instance1 = constructor.newInstance();// 通过反射获取LazyMan对象
        LazyMan instance2 = constructor.newInstance();// 通过反射获取LazyMan对象
        System.out.println(instance1);
        System.out.println(instance2);

    }
}
